package com.yanx.system.web.infra.listener;

import com.yanx.common.utils.String_;
import com.yanx.system.base.domain.entity.SysDept;
import com.yanx.system.base.domain.event.SysDeptSaveEvent;
import com.yanx.system.base.domain.manager.SysDeptManager;
import com.yanx.system.web.infra.constant.UserConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 监听系统配置，更新缓存
 *
 * @author gotanks
 * @date 2023/06/07
 */
@Slf4j
@Component
public class SysDeptListener {

    @Autowired
    private SysDeptManager sysDeptManager;

    @Async
    @Transactional
    @TransactionalEventListener
    public void onSysDeptSave(SysDeptSaveEvent event) {
        SysDept dept = event.getSysDept();
        // 如果该部门是启用状态，则启用该部门的所有上级部门
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())
                && String_.isNotEmpty(dept.getAncestors())
                && !String_.equals("0", dept.getAncestors())) {
            log.info("启用该部门的所有上级部门:{}", dept.getDeptName());
            sysDeptManager.updateParentDeptStatusNormal(dept.getAncestors());
        }
    }

}
